import { Component, OnInit } from '@angular/core';
import { MdlSnackbarService } from '@angular-mdl/core';
import { ConfirmationService, TreeNode, DialogService } from 'primeng/primeng';
import { DictService } from './service/dict.service';
import { flyIn } from '../../common/animation/common.animation';
import { DictDetailComponent } from './dict-detail.component';

@Component({
  templateUrl: './dict.component.html',
  styleUrls: ['./dict.component.scss'],
  providers: [DictService],
  animations: [flyIn]
})
export class DictComponent implements OnInit {
  allItems: any[];
  showItems: any[];
  selectedDict: any;
  searchItem: any = {};
  cols: any[] = [
    { field: 'seq', header: '序号', style: { 'width': '80px', 'text-align': 'center' } },
    { field: 'dictName', header: '名称' },
    { field: 'dictKey', header: '编码' }
  ];
  constructor(
    private dictService: DictService,
    private dialogService: DialogService,
    private mdlSnackbarService: MdlSnackbarService,
    private confirmationService: ConfirmationService) { }

  ngOnInit() {
    this.dictService.listAll().subscribe(data => {
      data.forEach((config, i) => config['seq'] = (i + 1));
      this.allItems = this.showItems = data;
    })
  }



  /** 修改 */
  update($event) {
    if (this.selectedDict) {
      const ref = this.dialogService.open(DictDetailComponent, {
        header: '编辑字典项',
        width: '850px',
        contentStyle: { 'height': '600px', 'padding': '0' },
        data: {
          'dictId': this.selectedDict.dictId,
          'sysId': this.selectedDict.sysId,
          'dictKey': this.selectedDict.dictKey
        }
      });
      ref.onClose.subscribe(data => {
        if (data) {
          this.ngOnInit();
          this.mdlSnackbarService.showToast("数据字典项保存成功！");
        }
      })
    }
  }
  /** 新增 */
  add($event) {
    const ref = this.dialogService.open(DictDetailComponent, {
      header: '新增字典项',
      width: '850px',
      contentStyle: { 'height': '600px', 'padding': '0' },
      data: {
      }
    });
    ref.onClose.subscribe(data => {
      if (data) {
        this.ngOnInit();
        this.mdlSnackbarService.showToast("数据字典项保存成功！");
      }
    })
  }

  /** 删除 */
  delete($event) {
    if (this.selectedDict) {
      this.confirmationService.confirm({
        header: '确认',
        message: '您确定要删除选择的记录吗？',
        accept: () => {
          this.dictService.deleteDict(this.selectedDict).subscribe(data => {
            this.ngOnInit();
            this.mdlSnackbarService.showToast("删除字典项成功！");
          });
        }
      });
    }
  }

}
